import { ipcMain, IpcMainEvent, IpcMainInvokeEvent } from "electron";
import {
  DeleteMessageByOne,
  DeleteMessagesByAll,
  FindAllMessageFile,
  GetChatMessage,
  GetMessageFileByFriend,
  GetMessageFileByGroup,
  GetMessageFileByOwner,
  UpdateMessageFilePath,
} from "../db/servers/message.ts";
import { ChatType, IMessage, IMessagePageInfo } from "../types/message.ts";
import { sendMessage } from "../ws";

export function MessageEvent() {
  // 发送消息给ws
  ipcMain.on("sendMessage", (_event: IpcMainEvent, data: IMessage) => {
    sendMessage(data);
  });

  // 获取本地message
  ipcMain.handle(
    "getChatMessage",
    (
      _event: IpcMainInvokeEvent,
      sessionId: string,
      ownerId: number,
      pageInfo: IMessagePageInfo,
    ) => {
      return GetChatMessage(sessionId, ownerId, pageInfo);
    },
  );

  // 删除单个消息
  ipcMain.handle(
    "deleteMessageByOne",
    (_event: IpcMainInvokeEvent, sessionId: string, ownerId: number) => {
      return DeleteMessageByOne(sessionId, ownerId);
    },
  );

  // 删除全部消息
  ipcMain.handle(
    "deleteMessageByAll",
    (_event: IpcMainInvokeEvent, userId: number, friendId: number, chatType: ChatType) => {
      return DeleteMessagesByAll(userId, friendId, chatType);
    },
  );

  // 查询全部文件
  ipcMain.handle(
    "findAllMessageFile",
    (_event: IpcMainInvokeEvent, userId: number, fileName: string) => {
      return FindAllMessageFile(userId, fileName);
    },
  );

  // 获取我的文件
  ipcMain.handle("getMessageFileByOnwer", (_event: IpcMainInvokeEvent, userId: number) => {
    return GetMessageFileByOwner(userId);
  });

  // 获取好友聊天文件
  ipcMain.handle(
    "getMessageFileByFriend",
    (_event: IpcMainInvokeEvent, userId: number, sessionId: string) => {
      return GetMessageFileByFriend(userId, sessionId);
    },
  );

  // 获取群聊天文件
  ipcMain.handle(
    "getMessageFileByGroup",
    (_event: IpcMainInvokeEvent, userId: number, sessionId: string) => {
      return GetMessageFileByGroup(userId, sessionId);
    },
  );

  // 更新文件本地路径
  ipcMain.handle(
    "updateMessageFilePath",
    (_event: IpcMainInvokeEvent, userId: number, sessionId: string, localPath: string) => {
      return UpdateMessageFilePath(userId, sessionId, localPath);
    },
  );
}
